<template>
  <div ref="imageWrapper">
    <a-card title="查询区域" class="search">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model ref="ruleForm" :model="queryParam" :rules="rules" layout="inline" @keyup.enter.native="onSearch">
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-model-item label="机构名称" prop="accName">
                <a-input v-model="queryParam.accName" readOnly placeholder="请选择" @click.native="openOrganModel" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-model-item label="审计时间" prop="arrayTime">
                <a-range-picker v-model="queryParam.arrayTime" format="yyyy-MM-DD" value-format="yyyy-MM-DD"
                  @change="handleDatechange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8" :offset="6">
              <span style="float: right; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" icon="search" class="yellow_search_btn" @click="onSearch">查询</a-button>
                <a-button icon="reload" class="clear_btn" @click="searchReset">清除条件</a-button>
                <a-button type="danger" :loading="ydLoading" @click="handleToYD(false)" icon="arrow-right"
                  style="margin-left: 18px">转疑点</a-button>
                <a-button v-if="isBackButton" type="primary" style="margin-left: 8px" @click="backUppage">
                  返回
                </a-button>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card v-if="modelData.length != 0" class="img_css" style="margin-top: 20px">
      <div class="Exceed_funds_map">
        <div class="title">
          <!-- <a-tooltip overlay-class-name="bgc_tooltip" placement="topRight">
            <template slot="title">
              <span>{{ modeltoop.mxms }}</span>
            </template>
            
          </a-tooltip> -->
          <span>
            {{ '未签合同先进场模型' }}
            <!-- <a-icon type="strikethrough" @click.stop="showImg" /> -->
          </span>
        </div>
        <div class="midline">
          <div class="line_v" />
          <div class="line_h" />
        </div>
        <div class="content_box">
          <div v-for="(item, index) in modelData" :key="index" class="content_item">
            <div class="line_v" />
            <div class="step3_left_left" :class="{ active: index === activeKey }" @click="getModelItem(index, item)">
              <div class="title">
                {{ item.modelName }}
              </div>
              <div class="count">
                {{ item.extraNum || 0 }}
              </div>
              <a-icon type="caret-down" class="logo" />
            </div>
          </div>
        </div>
      </div>
    </a-card>
    <a-card style="margin-top: 20px">
      <div>
        <a-table :columns="columns" :data-source="dataSource" row-key="chkin_odr_id" :bordered="true" :loading="loading"
          class="antableClass" :pagination="ipagination" :row-selection="rowSelection" @change="handleTableChange">
          <template slot="con_nm" slot-scope="text">
            <j-ellipsis :value="text" :length="10"></j-ellipsis>
          </template>
          <span slot="action" slot-scope="text, record">
            <a v-if="activeKey == 1" @click="handlerCheck(0, record)">分包队伍查看</a>
            <a v-if="activeKey == 2" @click="handlerCheck(1, record)">设备进场单查看</a>
            <a v-if="activeKey == 3" @click="handlerCheck(2, record)">物资点收单查看</a>
            <a-divider type="vertical" />
            <a @click="handlerCheck(3, record)">施工合同查看</a>
          </span>
        </a-table>
      </div>
    </a-card>
    <CheckOrganModal ref="departModal" @ok="updateQueryParam" />
    <YDModel ref="YDModel" :router-data="$route.path" />
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { httpAction, getAction, postAction, deleteAction } from '@/api/manage'
import CheckOrganModal from '@/views/sj/sjxmzygl/yzzx/testcomponent2/CheckOrganModal'
import { base64toImg } from '@/mixins/base64toImg'
import YDModel from '../fbzrgl/YDModel'
import html2canvas from 'html2canvas'
import { columns1, columns2, columns3, columns4 } from './columns'
import CheckRecord from './CheckRecord'
import jumpConfigMixin from '@/views/sj/sjxmzygl/sjxmss/jumpConfigMixin'
import _ from 'lodash'
export default {
  components: { CheckOrganModal, YDModel, CheckRecord },
  mixins: [JeecgListMixin, base64toImg, jumpConfigMixin],
  data() {
    return {
      queryParam: {
        accName: '',
        unitId: '',
        startTime: '',
        endTime: '',
        arrayTime: [],
      },
      superParam: {
        id: '95c255303b1effa0a9c12727a8b16470',
        modelId: 'e64079ce56a16f8c4cfc05519b6768cf',
        // extraFlag: true,
      },
      ydLoading: false,
      isBackButton: false,
      modelData: [
        {
          key: 'xmsl',
          modelName: '违规施工项目',
          extraNum: undefined,
        },
        {
          key: 'fbdwwt',
          modelName: '违规分包队伍引进',
          extraNum: undefined,
        },
        {
          key: 'sbzlwt',
          modelName: '违规设备租赁',
          extraNum: undefined,
        },
        {
          key: 'wzcgwt',
          modelName: '违规物资采购',
          extraNum: undefined,
        },
      ],
      dataSource: [],
      url: {
        list: '/sjmx/queryWqhtxjcmxNum',
        /**
         * 0:查询违规施工项目
         * 1:查询违规分包队伍引进
         * 2:查询违规设备租赁
         * 3:查询违规物资采购
         */
        modelUrlList: ['/sjmx/queryWqhtxjcmx', '/sjmx/queryWgfbdwyj', '/sjmx/queryWgsbzl', '/sjmx/queryWgwzcg'],
        detail: '/sjmx/queryProInfoById',
        // 查询模型转疑点信息(多选)
        TurnSuspects: '/sjmx/queryModelMsgMulti',
      },
      currentUrl: '',
      routerParams: [
        { id: 'c720b7b884e22dfcb930ceb1004fc781', pid: 'e64079ce56a16f8c4cfc05519b6768cd' },
        { id: '046e213cb3bf146ec0dcb21132c23c57', pid: '046e213cb3bf146ec0dcb21132c2df3' },
        { id: 'db84130be400cb511726a5fb5ad61f25', pid: '0' },
        { id: '02fe3cb18885c126aedcacf2ee74e429', pid: '0' },
      ],
      activeKey: null,
      rules: {
        accName: [{ required: true, message: '请选择机构名称' }],
        arrayTime: [{ required: true, message: '请选择审计时间' }],
      },
      columnsList: [columns1, columns2, columns3, columns4],
      columns: [],
      selectedRows: [],
      selectedRowKeys: ['PMM01_06273de8-7489-4a35-9754-17b9ab886051'],
      disableMixinCreated: true,
    }
  },
  created() {
    // this.getModelNum()
  },
  filters: {
    TimerFormat(time) {
      return time.indexOf(' ') ? time.split(' ')[0] : time
    },
  },
  watch: {
    selectedRowKeys(val) {
      console.log('selectedRowKeys====================', val)
    },
    $route: {
      handler: function (to) {
        if (Object.keys(to.query).length) {
          let query = _.cloneDeep(to.query)
          let selectedRowKeys = query.selectedRowKeys.split(',') || []
          query.selectedRowKeys && delete query.selectedRowKeys
          let activeKey = query.activeKey || '0'
          query.activeKey && delete query.activeKey
          this.queryParam = Object.assign({}, this.queryParam, query)
          this.queryParam.arrayTime = query.arrayTime.split(',')
          this.$nextTick(async () => {
            await this.getModelNum()
            this.getModelItem(activeKey, this.modelData[activeKey])
            this.selectedRowKeys = [...selectedRowKeys]
          })
        } else if (Object.keys(to.params).length && to.params.from == 'sjxmss') {
          let { accName, unitId } = to.params
          this.queryParam.accName = accName
          this.queryParam.unitId = unitId
          let { endDate, startDate } = JSON.parse(to.params.returnRecord)
          debugger
          this.queryParam.endTime = endDate
          this.queryParam.startTime = startDate
          this.queryParam.arrayTime = [startDate,endDate]
          this.$nextTick(() => {
            // 这可能存在问题
            this.onSearch()
          })
          this.isBackButton = true
          this.returnRecord = to.params.returnRecord
        }
      },
      immediate: true,
    },
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          debugger
          this.selectedRowKeys = [...selectedRowKeys]
          this.selectedRows = [...selectedRows]
        },
      }
    },
  },
  methods: {
    handleDetail(record) {
      getAction(this.url.detail, Object.assign({}, this.queryParam, { projectId: record.proj_id })).then((res) => {
        let data = res.result.records[0]
        this.$refs.CheckRecord.check(data)
      })
    },
    handlerCheck(num, record) {
      if ((num == 3 && record.con_nm) || num != 3) {
        //施工合同查看(3)并且有合同
        this.$router.push({
          path: '/sjxmzygl/yzzx/sbwzyz',
          query: {
            ...this.routerParams[num],
            record: JSON.stringify(record),
          },
        })
      } else {
        this.$message.warning('合同不存在')
      }
    },
    getModelItem(index, item) {
      if (item.extraNum) {
        this.flag = false
        this.activeKey = Number(index)
        this.columns = this.columnsList[index]()
        this.currentUrl = this.url.modelUrlList[index]
        this.selectedRows = []
        this.selectedRowKeys = []
        this.getModelData(this.currentUrl, this.getQueryParams(), 1)
      } else {
        this.$message.warning(item.modelName + '没有数据')
      }
    },
    searchReset() {
      this.queryParam = {
        accName: '',
        unitId: '',
      }
      this.modelData = _.cloneDeep(this.$options.data().modelData)
      this.dataSource = []
      this.activeKey = null
      this.flag = false
    },
    onSearch() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.getModelNum()
        }
      })
      console.log(this.queryParam)
    },
    getModelNum() {
      this.activeKey = null
      this.modelData = this.$options.data().modelData
      const params = Object.assign({}, this.queryParam, this.superParam)
      return getAction(this.url.list, params).then((res) => {
        if (res.success) {
          let data = res.result.records[0]
          Object.keys(data).map((item) => {
            this.modelData.map((itemobj) => {
              if (item == itemobj.key) {
                itemobj.extraNum = data[item]
              }
            })
          })
        }else{
           this.$message.error(res.message)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      })
    },
    getModelData(url, params, arg) {
      this.dataSource = []
      this.loading = true
      if (arg === 1) {
        this.ipagination.current = 1
      }
      getAction(url, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
          this.loading = false
        }else{
           this.$message.error(res.message)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      })
    },
    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      // TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.getModelData(this.currentUrl, this.getQueryParams())
    },
    // showImg() {
    //   this.$refs.businesschart.show()
    //      this.$message.warning('请先配置查询条件')
    // },
    openOrganModel() {
      this.$refs.departModal.edit()
    },
    updateQueryParam(data) {
      console.log(data, 'daat')
      this.queryParam.unitId = data.orgId
      this.queryParam.accName = data.orgName
    },
    handleToYD(record) {
      if (this.dataSource.length) {
        const { startTime = '', endTime = '' } = this.queryParam
        let ydnr = undefined
        let gzzd = undefined
        let time = `【${startTime}～${endTime}】【未签合同先进场模型】`
        console.log('this.activeKey------>', this.activeKey)
        let param = Object.assign({}, this.queryParam, { activeKey: this.activeKey }, this.superParam, {
          selectedRowKeys: this.selectedRowKeys.join(','),
        })
        let ydList = JSON.stringify(this.selectedRows)
        postAction(this.url.TurnSuspects, Object.assign({}, this.queryParam, this.superParam, { ydList: ydList })).then(
          (res) => {
            if (res.success) {
              if (res.result.length) {
                ydnr = res.result[0].ydms ? res.result[0].ydms : ydnr
                gzzd = res.result[0].gzzd ? res.result[0].gzzd : gzzd
              }
              this.addYd(param, ydnr, time, gzzd)
            }
            if (res.code === 510) {
              this.$message.warning(res.message)
            }
          }
        )
      } else {
        this.$message.error('空数据不能新建疑点')
      }
    },
    addYd(record, ydnr, time, gzzd) {
      this.ydLoading = true
      html2canvas(this.$refs.imageWrapper).then((canvas) => {
        let dataURL = canvas.toDataURL('image/png')
        console.log('父组件调用完了')
        this.$refs.YDModel.show(record, dataURL, ydnr, time, gzzd)
        this.ydLoading = false
      })
    },
    handleDatechange(dates) {
      this.queryParam.startTime = dates[0]
      this.queryParam.endTime = dates[1]
    },
  },
}
</script>
<style lang="less">
.bgc_tooltip {
  .ant-tooltip-inner {
    // 这里是框框
    border-radius: 20px;
    color: #333;
    width: 400px;
    padding: 10px 15px;
    background-color: rgba(255, 255, 255, 0.274) !important;
  }

  .ant-tooltip-arrow::before {
    // 这里是小三角形
    background-color: #fff !important;
  }
}
</style>
<style lang="less" scoped>
@import '~@assets/less/tableTheme.less';

.img_css /deep/ .ant-card-body {
  padding-top: 7px;
}

/deep/ .ant-table-thead {
  tr {
    th {
      text-align: center !important;
    }
  }
}

.Exceed_funds_map {
  width: 100%;
  position: relative;

  .title {
    // width: 350px;
    height: 50px;
    text-align: center;
    margin: 0 auto;

    padding-top: 7px;

    span {
      border-bottom-left-radius: 30px;
      border-bottom-right-radius: 30px;
      font-size: 22px;
      color: white;
      padding: 10px 35px 15px;
      background-color: rgb(1, 69, 142);
    }
  }

  .midline {
    margin: 0 auto;
    width: 93.8%;
    height: 40px;

    .line_v {
      margin: 0 auto;
      width: 4px;
      height: 36px;
      border-left: 2px dotted rgb(1, 69, 142);
    }

    .line_h {
      margin: 0 auto;
      width: 80%;
      border-bottom: 2px dotted rgb(1, 69, 142);
    }
  }

  .content_box {
    width: 100%;
    display: flex;
    justify-content: space-around;

    .content_item {
      display: flex;
      flex-direction: column;
      justify-content: flex-start;

      .line_v {
        margin: 0 auto;
        height: 15px;
        width: 4px;
        border-left: 2px dotted rgb(1, 69, 142);
      }

      display: flex;
      justify-content: space-around;
      align-items: center;

      .step3_left_left {
        // flex-shrink:1;
        width: 200px;
        height: 70px;
        border: 2px solid #000e89;
        font-size: 16px;
        font-weight: 700;
        color: white;
        text-align: center;
        cursor: pointer;

        .title {
          height: 35px;
          line-height: 20px;
          background-color: rgb(1, 69, 142);
        }

        .count {
          line-height: 30px;
          height: 31px;
          color: rgb(1, 69, 142);
        }

        .logo {
          position: relative;
          top: -5px;
          color: #fff;
        }
      }

      .step3_left_left {
        margin-left: 10px;
      }
    }
  }

  .active {
    .title {
      background-color: rgb(236, 149, 54) !important;
      height: 30px;
      padding-bottom: 10px !important;
    }

    .count {
      color: orange !important;
      background-color: rgb(253, 245, 236);
    }

    .logo {
      color: rgb(236, 149, 54) !important;
    }

    border: 2px solid #ec9536 !important;
  }
}
</style>
